package com.ideal.hadoopadmin.web.controller.report;

import com.github.pagehelper.PageInfo;
import com.ideal.hadoopadmin.entity.meta.hive.MetaHiveInfo;
import com.ideal.hadoopadmin.framework.page.Page;
import com.ideal.hadoopadmin.service.meta.hive.MetaHiveInfoService;
import com.ideal.hadoopadmin.web.controller.UIController;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

/**
 * Created by 袁颖 on 2016/5/10.
 */
@Controller
@RequestMapping(HiveTableAccessContrller.PORTAL_PREFIX)
public class HiveTableAccessContrller extends UIController {
    public static final String PORTAL_PREFIX = "/report/hiveTableAccess";
    private final static Logger logger = LoggerFactory.getLogger(HiveTableAccessContrller.class);
    @Resource
    private MetaHiveInfoService hiveInfoService;

    @RequestMapping("hiveTableAccess_list")
    public void hdfsPathAccess(HttpServletRequest request) throws Exception{
        Map<String, Object> searchParam = WebUtils.getParametersStartingWith(request, "Q_");
        //默认不加载数据，只有当点击搜索的时候，才加载数据
        if(null != request.getParameter("isQuery") && "query".equals(request.getParameter("isQuery").toString())){
            PageInfo page = hiveInfoService.searchReportPage(Page.getCurrentPage(request), Page.DEFAULT_PAGESIZE, searchParam);
            request.setAttribute("page", page);
        }
        List<MetaHiveInfo> metaHiveInfos = hiveInfoService.findAllHiveInfo();
        request.setAttribute("metaHiveInfos", metaHiveInfos);
    }

    /**
     * hvie报表（用户主导）第一级数据
     * add20160918qinfengxia
     * @param request
     * @throws Exception
     */
    @RequestMapping("hiveUserAccess_list")
    public void hdfsUserAccess(HttpServletRequest request) throws Exception{
        Map<String, Object> searchParam = WebUtils.getParametersStartingWith(request, "Q_");
        //默认不加载数据，只有当点击搜索的时候，才加载数据
        if(null != request.getParameter("isQuery") && "query".equals(request.getParameter("isQuery").toString())){
            PageInfo page = hiveInfoService.searchHiveUserPage(Page.getCurrentPage(request), Page.DEFAULT_PAGESIZE, searchParam);
            request.setAttribute("page", page);
        }
//        List<MetaHiveInfo> metaHiveInfos = hiveInfoService.findAllHiveInfo();
//        request.setAttribute("metaHiveInfos", metaHiveInfos);
    }
    /**
     * hive第二级数据（权限）
     * add20160721qinfengxia
     * @param clusterUserId
     * @param tableName
     * @return
     */
    @RequestMapping("hiveTableAccessChild_list")
    @ResponseBody
    public List<Map<String,Object>> hiveTableAccessChild(Integer clusterUserId,String tableName){
        List<Map<String,Object>> hiveTableAccessChild = hiveInfoService.searchReportChildPage(clusterUserId,tableName);
        return hiveTableAccessChild;
    }

    /**
     * hive（用户主导）第二级数据（权限）
     * add20160918qinfengxia
     * @param clusterUserId
     * @param tableName
     * @return
     */
    @RequestMapping("hiveUserAccessChild_list")
    @ResponseBody
    public List<Map<String,Object>> hiveUserAccessChild(Integer clusterUserId,String tableName){
        List<Map<String,Object>> hiveUserAccessChild = hiveInfoService.searchHiveUserChildPage(clusterUserId, tableName);
        return hiveUserAccessChild;
    }
    @RequestMapping("downReport")
    public void downReport(HttpServletRequest request){
        /*
        * 1.先根据hdfsPath进行过滤
        * */
        Map<String, Object> searchParam = WebUtils.getParametersStartingWith(request, "Q_");
//        hiveInfoService.downReport(searchParam);
     }
    /**
     * 如何将java对象中的数值放入每一行里面,反射机制?
     */
    public HSSFWorkbook excelPrint(List<Object> objects) {
        String[] filedNames = getFiledName(objects);
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();//创建excel文件
        HSSFSheet hssfSheet = hssfWorkbook.createSheet();//创建一个sheet
        for (int i = 0; i < filedNames.length; i++) {
            hssfSheet.setColumnWidth(i, 800);//统一设置列宽
        }
        HSSFRow hssfRow0 = hssfSheet.createRow(0);//设置第一行
        for (int i = 0; i < filedNames.length; i++) {
            hssfRow0.createCell(i).setCellValue(filedNames[i]);
        }
        for (int i = 1; i < objects.size(); i++) {
            HSSFRow hssfRow = hssfSheet.createRow(i);//创建行,设置其余的行
            for (int j = 0; j < filedNames.length; j++) {
                try {
                    hssfRow.createCell(j).setCellValue((String) getFiledValueByObjectIndex(objects.get(i), j));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return hssfWorkbook;
    }

    /**
     * 使用反射根据属性名称获取属性值
     *
     * @param fieldName 属性名称
     * @param o         操作对象
     * @return Object 属性值
     */
    private Object getFieldValueByName(String fieldName, Object o) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter, new Class[]{});
            Object value = method.invoke(o, new Object[]{});
            return value;
        } catch (Exception e) {
            System.out.println("属性不存在");
            return null;
        }
    }
    /***********************一些公用方法***************************/
    /**
     * 根据对象获取属性名
     *
     * @param o
     * @return
     */
    private String[] getFiledName(Object o) {
        Field[] fields = o.getClass().getDeclaredFields();
        String[] fieldNames = new String[fields.length];
        for (int i = 0; i < fields.length; i++) {
            fieldNames[i] = fields[i].getName();
        }
        return fieldNames;
    }

    /**
     * 根据对象里面属性的位置获取的属性值
     *
     * @param o     对象
     * @param index 下标,即对象里属性位置
     * @return
     */
    private Object getFiledValueByObjectIndex(Object o, int index) throws Exception {
        Field[] fields = o.getClass().getDeclaredFields();
        String[] fieldNames = new String[fields.length];
        for (int i = 0; i < fields.length; i++) {
            fieldNames[i] = fields[i].getName();
        }
        String firstLetter = fieldNames[index].substring(0, 1).toUpperCase();
        String getter = "get" + firstLetter + fieldNames[index].substring(1);
        try {
            Method method = o.getClass().getMethod(getter, new Class[]{});
            Object value = method.invoke(o, new Object[]{});
            return value;
        } catch (Exception e) {
            logger.error("####HiveTableAccessController:" + e);
            throw e;
        }

    }

    /**
     * ************************************************
     */
    @Override
    public String getPortalPrefix() {
        return PORTAL_PREFIX;
    }

    /**
     * 下载结果
     * add20160721qinfengxia
     * @param response
     * @param tableName
     */
    @RequestMapping("down_all")
    public void downAll(HttpServletResponse response,String tableName) {
        List<Map<String,Object>> hiveList = hiveInfoService.queryHiveByDown(tableName);
        OutputStream outputStream = null;
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=hive_list.xls");
            HSSFWorkbook hssfWorkbook = hiveInfoService.creatSheet(hiveList);
            outputStream = response.getOutputStream();
            hssfWorkbook.write(outputStream);
            response.flushBuffer();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 下载结果
     * add20160918qinfengxia
     * @param response
     * @param userName
     */
    @RequestMapping("down_all_hive_user")
    public void downAllHiveUser(HttpServletResponse response,String userName) {
        List<Map<String,Object>> hiveList = hiveInfoService.queryHiveUserByDown(userName);
        OutputStream outputStream = null;
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=hive_list.xls");
            HSSFWorkbook hssfWorkbook = hiveInfoService.creatSheetHiveUser(hiveList);
            outputStream = response.getOutputStream();
            hssfWorkbook.write(outputStream);
            response.flushBuffer();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
